package com.study.tiger.controller;

import com.study.tiger.pojo.BaseParam;
import com.study.tiger.pojo.JWTInfo;
import com.study.tiger.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: liutingting
 * @Date: 2022/3/4 000410:42
 * @Version: 1.0
 */
@RestController
@RequestMapping("/v1/userinfo")
@Api(tags="登录API")
public class LoginController {

    @Autowired
    private TokenUtil tokenUtil;

    @Value("${token.expire}")
    private int expire;

    @Value("${REDIS_HOST}")
    private String test;

    @GetMapping("/token")
    @ApiOperation(value = "生成token")
    public String getToken(){
        JWTInfo jwtInfo = new JWTInfo("3381726721693712519", "lsddj18606501017");
        String token = tokenUtil.generateToken(jwtInfo, expire);
        return token;
    }

    @PostMapping(value = "/login")
    public String login(@RequestBody BaseParam baseParam, HttpServletRequest request, HttpServletResponse response) throws Exception {

        ServletContext servletContext = request.getServletContext();
        if (baseParam.getPhoneNo() != "12345678912") {
            return "用户不存在!";
        }
        //效验账号是否锁定
        if(!checkLock(servletContext, baseParam.getPhoneNo())) {
            return "该账号已被锁定5分钟!";
        }
        if (!baseParam.getPassword().equalsIgnoreCase("123456")) {
            //插入错误记录
            addFailNum(servletContext, baseParam.getPhoneNo());
            return "密码错误!";
        }
        /*if (1 != employee.getStatus()){
            return Result.ERROR("账号被禁用!");
        }*/
        //登录成功,清空登录失败记录
        cleanFailNum(servletContext, baseParam.getPhoneNo());
        return "OK";
    }

    /**
     * 校验用户登录失败次数
     * @param servletContext
     * @param phoneNo
     * @return
     */
    private boolean checkLock(ServletContext servletContext, String phoneNo) {
        Object obj = servletContext.getAttribute(phoneNo);
        if (obj == null) {
            return true;
        }
        /*JSONObject json = JSON.parseObject(JSON.toJSONString(obj));
        Integer num = json.getInteger("num");
        Date date = json.getDate("lastDate");
        long timeDifference = ((new Date().getTime() - date.getTime()) / 60 / 1000);
        return num < 3 || timeDifference >= 5;*/
    }

    /**
     * 新增用户登录失败次数
     * @param servletContext
     * @param phoneNo
     */
    private void addFailNum(ServletContext servletContext, String phoneNo) {
        Object obj = servletContext.getAttribute(phoneNo);
        JSONObject json;
        int num = 0;
        if (obj == null) {
            json = new JSONObject();
        } else {
            json = JSON.parseObject(JSON.toJSONString(obj));
            num = json.getInteger("num");
            Date date = json.getDate("lastDate");
            long timeDifference = ((new Date().getTime() - date.getTime()) / 60 / 1000);
            if (timeDifference >= 5) {
                num = 0;
            }
        }
        json.put("num", num + 1);
        json.put("lastDate", new Date());
        servletContext.setAttribute(phoneNo, json);
    }

    /**
     * 清理用户登录失败的记录
     * @param servletContext
     * @param phoneNo
     */
    private void cleanFailNum(ServletContext servletContext, String phoneNo) {
        servletContext.removeAttribute(phoneNo);
    }


}
